<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElInput, ElButton, ElTable, ElPagination, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'; 

const router = useRouter()

// 状态管理
const activeTab = ref('records')      
const deleteUsername = ref('')    //存储要删除的用户名
const searchKeyword = ref('')     //搜索关键词

const currentPage = ref(1)       //分页控制
const pageSize = ref(10)         //每页显示条数

// 真实数据存储
const detectionRecords = ref<any[]>([])  //检测记录列表
const usersList = ref<any[]>([])         //用户列表

// 分页控制（用户管理）相关
const currentPageUser = ref(1)   //用户列表当前页码
const pageSizeUser = ref(10)     //每页显示条数

// 统计数据
const totalUsers = ref(0)       //用户总数
const todayTests = ref(0)       //今日检测数

// 获取检测记录列表
const fetchDetectionRecords = async () => {
  try {
    //发送get请求获取检测记录，携带token验证身份
    const response = await axios.get('/admin/records', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}` //从本地存储获取Token
      }
    });
    // 校验数据格式，将用户名合并到每条记录中
    if (!response.data?.records) {
      throw new Error('返回数据格式不正确，缺少records字段');
    }
    //处理数据：解析预测结果，提取最高概率疾病和置信度
    detectionRecords.value = Array.isArray(response.data.records) 
      ? response.data.records.map((record: any) => ({
          ...record,    //保留原始字段
          user: record.username,   //简化用户名
          prediction: {
            // 从预测结果中提取最高概率疾病和置信度
            disease_prediction: Object.entries(JSON.parse(record.prediction))
              .sort((a: [string, any], b: [string, any]) => Number(b[1]) - Number(a[1])) //按概率降序排序
              .map(([k]) => k)[0],    //提取最高概率疾病名称
            confidence: Math.max(...Object.values(JSON.parse(record.prediction))),    //计算最高概率
            detail: {   //存储完整概率详情
              probabilities: JSON.parse(record.prediction)
            }
          }
        }))
      : [];    //若数据不是数组则设为空
    todayTests.value = response.data.counts;  //今日检测数
  } catch (error: any) {
    console.error('获取检测记录失败：', error);
    //优先后端
    ElMessage.error('获取检测记录失败: ' + 
      (error.response?.data?.detail || error.message));
  }
};

// 获取用户列表
const fetchUsers = async (role?: string) => {   //角色筛选
  try {
    const response = await axios.get('/admin/users', {
      params: { role },   //传递筛选参数
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      }
    });
    usersList.value = response.data.users;   //存储用户列表
    totalUsers.value = usersList.value.length;  //更新总用户数
  } catch (error: any) {
    console.error('获取用户信息失败：', error);
    ElMessage.error('获取用户信息失败: ' + 
      (error.response?.data?.detail || error.message));
  }
};

// 初始化数据，可在组件挂载时调用
onMounted(() => {
  fetchDetectionRecords();     //加载检测记录
  fetchUsers();                //加载用户列表
  
});

// 计算属性 - 过滤后的记录
const filteredRecords = computed(() => {
  if (!searchKeyword.value) return detectionRecords.value;    //没有关键词返回全部
  
  const keyword = searchKeyword.value.toLowerCase();   //忽略大小写
  return detectionRecords.value.filter(record => 
  //匹配用户名、检测时间、检测结果
    record.user?.toLowerCase().includes(keyword) || 
    record.created_at?.toLowerCase().includes(keyword) || 
    record.prediction.disease_prediction?.toLowerCase().includes(keyword)
  );
});

// 计算属性 - 分页后的记录列表
const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value; //计算起始索引
  const end = start + pageSize.value;   //计算结束索引
  return filteredRecords.value.slice(start, end);  //截取当前页数据
});

// 计算属性 - 分页后的用户列表
const paginatedUsers = computed(() => {
  const start = (currentPageUser.value - 1) * pageSizeUser.value;
  const end = start + pageSizeUser.value;
  return usersList.value.slice(start, end);
});

// 分页控制（检测记录）
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;  //更新每页显示条数
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;    //更新当前页码
};

// 分页控制（用户管理）
const handleSizeChangeUser = (newSize: number) => {
  pageSizeUser.value = newSize;
};
const handleCurrentChangeUser = (newPage: number) => {
  currentPageUser.value = newPage;
};

// 搜索记录
const filterRecords = () => {
  currentPage.value = 1; // 重置到第一页
  fetchDetectionRecords(); // 重新获取数据
};

// 删除用户
const deleteUser = async () => {
  if (!deleteUsername.value) {   
    ElMessage.warning('请输入要删除的用户名');
    return;
  }
  
  try {
    await axios.delete('/admin/users', {
      params: { username: deleteUsername.value },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      }
    });
    await fetchUsers();
    ElMessage.success(`已删除用户：${deleteUsername.value}`);    //提示
    deleteUsername.value = '';   //清空输入框
  } catch (error) {
    console.error('删除用户失败：', error);
    const errMsg = (error as any).response?.data?.detail || '删除用户失败';
    ElMessage.error(errMsg);
  }
};

// 确认删除
const confirmDelete = (username: string) => {
  if (window.confirm(`确定要删除用户 ${username} 吗？`)) {
    deleteUsername.value = username;
    deleteUser();
  }
};

// 查看详情
const viewDetails = (record: any) => {
  const details = {
    '记录ID': record.record_id,
    '用户名': record.user,
    '检测时间': record.created_at,
    '预测结果': record.prediction.disease_prediction,
    '置信度': record.prediction.confidence,
    '详细概率': Object.entries(record.prediction.detail.probabilities as Record<string, number>)
      .map(([k, v]: [string, number]) => `${k}: ${(v * 100).toFixed(2)}%`)
      .join('\n')
  };
  console.log(details);
  alert(`检测记录详情：\n${JSON.stringify(details, null, 2)}`);
};
</script>
<template>
  <div class="home-container">
    <div class="content-left">
      <h1 class="glitch-title">管理员控制台</h1>
      
      <!-- 导航菜单 -->
      <div class="admin-nav">
        <el-button 
          class="tech-button outline" 
          @click="activeTab = 'records'"
          :class="{ 'active': activeTab === 'records' }"
        >
          检测记录
        </el-button>
        <el-button 
          class="tech-button outline" 
          @click="activeTab = 'users'"
          :class="{ 'active': activeTab === 'users' }"
        >
          用户管理
        </el-button>
      </div>
      
      <!-- 内容区域 -->
      <div class="admin-content">
        <!-- 检测记录面板 -->
        <div v-if="activeTab === 'records'">
          <div class="record-filter">
            <el-input 
              v-model="searchKeyword" 
              placeholder="搜索用户名/时间" 
              class="tech-input" 
              @keyup.enter="filterRecords"
            />
            <el-button 
              class="tech-button" 
              @click="filterRecords"
            >
              搜索
            </el-button>
          </div>
          
          <div class="record-list">
            <el-table 
              :data="paginatedRecords" 
              stripe 
              border
              class="tech-table"
            >
              <el-table-column prop="user" label="用户名" />
              <el-table-column prop="created_at" label="检测时间" />
              <el-table-column prop="prediction.disease_prediction" label="检测结果" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click="viewDetails(scope.row)"
                  >
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 检测记录分页控件 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredRecords.length"
              style="margin-top: 20px;"
            ></el-pagination>
          </div>
        </div>
        
        <!-- 用户管理面板 -->
        <div v-else-if="activeTab === 'users'">
          <div class="user-management">
            <el-input 
              v-model="deleteUsername" 
              placeholder="输入要删除的用户名" 
              class="tech-input" 
              style="width: 240px;"
            />
            <el-button 
              type="danger" 
              class="tech-button" 
              @click="deleteUser"
            >
              删除用户
            </el-button>
            
            <el-table 
              :data="paginatedUsers" 
              stripe 
              border
              class="tech-table"
              style="margin-top: 20px;"
            >
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="role" label="用户角色" />
              <el-table-column prop="created_at" label="注册时间" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="confirmDelete(scope.row.username)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 用户管理分页控件 -->
            <el-pagination
              @size-change="handleSizeChangeUser"
              @current-change="handleCurrentChangeUser"
              :current-page="currentPageUser"
              :page-sizes="[10, 20, 30]"
              :page-size="pageSizeUser"
              layout="total, sizes, prev, pager, next, jumper"
              :total="usersList.length"
              style="margin-top: 20px;"
            ></el-pagination>
          </div>
        </div>
      </div>
      
    </div>
    
    <!-- 右侧内容区域 -->
    <div class="content-right">
      <div class="admin-summary">
        <div class="summary-card">
          <div class="card-title">总用户数</div>
          <div class="card-value">{{ totalUsers }}</div>
        </div>
        <div class="summary-card">
          <div class="card-title">今日检测</div>
          <div class="card-value">{{ todayTests }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 复用首页的基础布局样式 */
.home-container {
  display: flex;
  max-width: 1200px;
  width: 100vw;
  margin: 0 auto;
  padding: 40px 20px; 
  min-height: 75vh;
  background: #f9fcff;
}

.content-left {
  flex: 0 0 60%;
  padding-right: 40px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.content-right {
  flex: 1;
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  justify-content: center;
}

/* 复用标题样式 */
.glitch-title {
  font-size: 2.4rem;
  font-weight: 700;
  margin-bottom: 25px;
  background: linear-gradient(90deg, #165DFF 0%, #36D399 100%);
  -webkit-background-clip: text; 
  background-clip: text;   
  color: transparent;   
  position: relative;
  text-shadow: 
    0 0 10px rgba(22,93,255,0.2),   
    0 0 20px rgba(54,211,153,0.2);
  animation: glitch 3s infinite;   
}

@keyframes glitch {
  0% { transform: translate(0,0); }
  2% { transform: translate(-2px,2px); opacity: 0.9; }
  4% { transform: translate(2px,-2px); opacity: 0.9; }
  6% { transform: translate(-2px,-2px); opacity: 0.9; }
  8% { transform: translate(2px,2px); opacity: 0.9; }
  10% { transform: translate(0,0); opacity: 1; }
  100% { transform: translate(0,0); }
}

/* 导航菜单样式 */
.admin-nav {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.admin-nav .tech-button.outline.active {
  background: rgba(22,93,255,0.1);
  box-shadow: 0 4px 12px rgba(22,93,255,0.2);
}

/* 搜索区域样式 */
.record-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 表格样式 */
.tech-table {
  margin-bottom: 20px;
}

/* 统计卡片样式 */
.admin-summary {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 20px;
  width: 100%;
}

.summary-card {
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  text-align: center;
  height: 130px;
}

.card-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  background: linear-gradient(90deg, #165DFF, #36D399);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

/* 复用按钮样式 */
.tech-button {
  padding: 12px 30px;
  border-radius: 25px;
  border: none;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);  
  background: linear-gradient(90deg, #165DFF, #36D399);  
  color: #fff;
  font-weight: 500;
  box-shadow: 0 8px 25px rgba(22,93,255,0.3); 
}

.tech-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(22,93,255,0.4);
}

.tech-button.outline {
  background: transparent;
  color: #165DFF;
  border: 2px solid #165DFF;
  box-shadow: none;
}

.tech-button.outline:hover {
  background: rgba(22,93,255,0.1);
  box-shadow: 0 8px 25px rgba(22,93,255,0.2);
}

/* 复用输入框样式 */
.tech-input {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  transition: all 0.3s;  
}

.tech-input:focus {
  border-color: #165DFF;
  box-shadow: 0 0 0 4px rgba(22,93,255,0.1);
}
</style>